package com.example.a24porint;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


public class waitingroom extends AppCompatActivity {
    private Socket socket =null;
    private OutputStream outputStream;
    private InputStream inputStream;
    private BufferedReader in;
    private ListView ol;
    private String[] data = {"apple","bannner","orange","watermelon","pear","grape",
            "pineapple","strawberry","cherry","mango","apple","bannner","orange",
            "watermelon","pear","grape", "pineapple","strawberry","cherry","mango"
    };
    private Button accinvitebt;
    private Button refreshbt;
    private Button lookrankbt;
    private TextView inviteman;
    private String invitemanname="";
    private boolean oktosend=false;
    class MyClass extends TimerTask {
        Timer timer=null;
        public MyClass(){}
        public MyClass(Timer timer)
        {
            this.timer=timer;
        }
        @Override
        public void run()
        {
            oktosend=true;
            timer.cancel();
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_waitingroom);
        ApplicationUtil appUtil = (ApplicationUtil) waitingroom.this.getApplication();
        try {
            appUtil.init();
            socket = appUtil.getSocket();
            outputStream=appUtil.getOutputStream();
            inputStream=appUtil.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        ol=findViewById(R.id.onlinelist);
        inviteman=findViewById(R.id.textView3);
        accinvitebt=findViewById(R.id.button13);
        refreshbt=findViewById(R.id.button14);
        lookrankbt=findViewById(R.id.button17);
        lookrankbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Intent i = new Intent(waitingroom.this,lookrankwindow.class); //切换窗口
                //startActivity(i);
            }
        });
        refreshbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(oktosend) {
                    oktosend=false;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                String str = "refresh";
                                str += invitemanname;
                                byte[] str_head = str.getBytes();
                                outputStream.write(str_head);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            return;
                        }
                    }).start();
                    Timer mTimer =new Timer();
                    mTimer.schedule(new MyClass(mTimer),1000);
                }
            }
        });
        accinvitebt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                if(invitemanname!=""&&oktosend)
                {
                    oktosend=false;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                String str="accinvite";
                                str+=invitemanname;
                                byte[] str_head=str.getBytes();
                                outputStream.write(str_head);
                                itsover=true;
                                //getinvitethread.stop();//停止线程
                                //in.close();
                                getinvitethread.join();
                                Intent i = new Intent(waitingroom.this,onlinegame.class); //切换窗口
                                startActivity(i);
                                Log.i("accinvitebttag","accinvitebtisok");
                            } catch (IOException | InterruptedException e) {
                                e.printStackTrace();
                            }
                            return;
                        }
                    }).start();
                    Timer mTimer =new Timer();
                    mTimer.schedule(new MyClass(mTimer),1000);
                }
            }
        });
        ol.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Toast.makeText(waitingroom.this, "选择了"+ String.valueOf(position)+"项", Toast.LENGTH_SHORT).show();
                Toast.makeText(waitingroom.this, "已发送邀请给"+ String.valueOf(position)+ parent.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
                sendinvite((String)parent.getItemAtPosition(position));
            }
        });
        init();
    }
    private void sendinvite(String name)
    {
        String[] str=new String[1];//="invite";
        str[0]="invite";
        str[0]+=name;
        if(oktosend) {
            oktosend=false;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        byte[] str_head = str[0].getBytes();
                        outputStream.write(str_head);
                        Log.i("sendinvitetag", "sendinvitebtisok");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return;
                }
            }).start();
            Timer mTimer =new Timer();
            mTimer.schedule(new MyClass(mTimer),1000);
        }
    }
    boolean itsover=false;
    Thread getinvitethread;
    private void getinvite()
    {
        final String[] receiveMsg = new String[1];
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                    while (true) {                   //步骤三
                        receiveMsg[0] = in.readLine();
                        if(itsover) {
                            Log.i("getintag","getinviteis over2");
                            return;
                        }
                        else if ((receiveMsg[0]) != null&&receiveMsg[0].charAt(0)=='k') {
                            Log.i("getintag","getinviteis over3");
                            return;
                        }
                        else if ((receiveMsg[0]) != null&&sbinvite(receiveMsg[0])) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(waitingroom.this, receiveMsg[0]+"邀请你", Toast.LENGTH_SHORT).show();
                                    invitemanname="";
                                    for(int i=6;i<receiveMsg[0].length();i++)invitemanname+=receiveMsg[0].charAt(i);
                                    inviteman.setText("邀请人"+invitemanname);
                                    receiveMsg[0]=null;
                                }
                            });
                        }
                        else if ((receiveMsg[0]) != null&&sbaccpet(receiveMsg[0])) {
                            Intent i = new Intent(waitingroom.this,onlinegame.class); //切换窗口
                            startActivity(i);
                            receiveMsg[0]=null;
                            return;
                        }
                        else if ((receiveMsg[0]) != null&&receiveMsg[0].length()>5) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    initlist(receiveMsg[0]);
                                    receiveMsg[0]=null;
                                }
                            });
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });//.start();
        getinvitethread=thread;
        thread.start();
    }
    private boolean sbaccpet(String s)
    {
        String str="accept";
        if(s.length()<str.length())return false;
        for(int i=0;i<str.length();i++)
        {
            if(str.charAt(i)!=s.charAt(i))
            {
                return false;
            }
        }
        return true;
    }
    private boolean sbinvite(String s)
    {
        String str="invite";
        if(s.length()<str.length())return false;
        for(int i=0;i<str.length();i++)
        {
            if(str.charAt(i)!=s.charAt(i))
            {
                return false;
            }
        }
        return true;
    }
    private void initlist(String s)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
            //receiveMsg[0]="fuck:adsijfoaefj,vasidcjvoawef,acivjaosjdrf,iacjvoa;";
                String[] data1=getonlineuser(s);
                if(data1==null)return;
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                        waitingroom.this,android.R.layout.simple_list_item_1,data1);
                ol.setAdapter(adapter);
            }
        });
    }

    private String[] getonlineuser(String str)//"online:askojdfoa,asdfijoasd,asdjfo,voasjdfoi,erwafopisdj;\r";
    {
        String[] arr;
        List list = new ArrayList();
        int p=0;
        if(str==null||str.length()==0)return null;
        //while(true)
        for(int i=0;i<str.length();i++)
        {
            if(str.charAt(i)==':') {
                p=i+1;
                break;
            }
            //p++;
        }
        if(p==0)return null;
        //p++;
        String name="";
        for(int i=p;i<str.length();i++)
        {
            if(str.charAt(i)==','||str.charAt(i)==';')
            {
                list.add(name);
                name="";
            }
            else
            {
                name+=str.charAt(i);
            }
        }
        arr=(String[])list.toArray(new String[list.size()]);
        return arr;
    }
    private void init()
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    oktosend=false;
                    String str="wait";
                    byte[] str_head=str.getBytes();
                    outputStream.write(str_head);
                    getinvite();
                    Log.i("inittag","initisok");
                    //initlist();
                    //initLoginThread();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }
        }).start();
        Timer mTimer =new Timer();
        mTimer.schedule(new MyClass(mTimer),500);
    }
}

/*String sss="sbinvite:asdf,ddasdf,asdfasdfewtretg,ergertvb,fbcxv,btr,h,fgdv;";
        String[] data1=getonlineuser(sss);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                waitingroom.this,android.R.layout.simple_list_item_1,data);
        ol=findViewById(R.id.onlinelist);
        ol.setAdapter(adapter);*/
    /*private void initlist1()
    {
        final String[] receiveMsg = new String[1];
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                    while (true) {                   //步骤三
                        if ((receiveMsg[0] = in.readLine()) != null&&receiveMsg[0].length()>5) {
                            break;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //receiveMsg[0]="fuck:adsijfoaefj,vasidcjvoawef,acivjaosjdrf,iacjvoa;";
                        String[] data1=getonlineuser(receiveMsg[0]);
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                                waitingroom.this,android.R.layout.simple_list_item_1,data1);
                        ol.setAdapter(adapter);
                    }
                });
            }
        }).start();
    }*/